import datetime

import jwt
from jwt import exceptions

JWT_SALT = 'Coderlz'


def set_token(payload, timeout=20):
    """
    :param payload: {'uid':1,'username':'coderlz'} 用户信息
    :param timeout:token的过期时间默认试20分钟
    """
    # headers = {
    # 	'typ': 'jwt',
    # 	'alg': 'HS256'
    # }
    payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(minutes=timeout)
    # payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(hours=24 * 7)
    token = jwt.encode(payload=payload, key=JWT_SALT, algorithm='HS256')
    return token


def parse_payload(token):
    result = {'status': False, 'data': None, 'error': None}
    try:
        verify_payload = jwt.decode(token, JWT_SALT, algorithms='HS256')
        # print(verify_payload)
        result['status'] = True
        result['data'] = verify_payload
    except exceptions.ExpiredSignatureError:
        result['error'] = "token已失效"
    except jwt.DecodeError:
        result['error'] = "token认证失败"
    except jwt.InvalidTokenError:
        result['error'] = "非法的token"

    return result
